<template>
  <div class="realEstate">
    <div class="layui-panel">
      <div class="p-12">
        <div class="title">车辆档案</div>
        <div class="pt-6">
          <form class="layui-form" action="">
            <div class="layui-row">
              <div class="layui-col-xs4">
                <div class="layui-form-item">
                  <label class="layui-form-label label-width">车牌号码</label>
                  <div class="layui-input-inline layui-input-wrap">
                    <input
                      type="text"
                      name="licPlateNum"
                      autocomplete="off"
                      lay-affix="clear"
                      placeholder="请输入 "
                      class="layui-input"
                    />
                  </div>
                </div>
              </div>
              <div class="layui-col-xs4">
                <div class="layui-form-item">
                  <label class="layui-form-label label-width">归管部门</label>
                  <div class="layui-input-inline layui-input-wrap">
                    <input
                      type="text"
                      name="registrationDept"
                      autocomplete="off"
                      lay-affix="clear"
                      placeholder="请输入 "
                      class="layui-input"
                    />
                  </div>
                </div>
              </div>
              <div class="layui-col-xs4">
                <button
                  class="layui-btn layui-btn-normal"
                  lay-submit
                  lay-filter="car-search"
                  type="button"
                >
                  <i class="layui-icon layui-icon-down layui-icon-search"></i>
                  搜索
                </button>
              </div>
            </div>
          </form>
        </div>
      </div>
    </div>
    <div class="layui-panel mt-20">
      <div class="flex-end mt-12 mr-12">
        <button
          type="button"
          class="layui-btn layui-bg-blue"
          lay-on="openDialog"
        >
          新增
        </button>
      </div>
      <div class="p-12">
        <table class="layui-hide" id="ID-table-demo-data"></table>
      </div>
    </div>
    <!-- 编辑栏 -->
    <div id="barDemo" style="display: none">
      <div class="layui-clear-space operates">
        <a class="layui-btn layui-btn-xs layui-bg-blue" lay-event="edit"
          >编辑</a
        >
        <a class="layui-btn layui-btn-xs layui-bg-blue" lay-event="del">删除</a>
      </div>
    </div>
    <compile v-show="false" ref="addDialog"></compile>
  </div>
</template>

<script>
import compile from "@/views/vehicleFile/components/VehicleEditing.vue";
import {
  addVehicleInfo,
  editVehicleInfo,
  delVehicleInfo,
  getImage,
} from "@/api/real_estate_ledger";
export default {
  components: {
    compile,
  },
  data() {
    return {
      addOfEdit: "",
      fileImage: "", // 图片链接
      fileId: "",
      departmentId: "",
      token: (localStorage.getItem('foxnic-web'))?.token || "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJhbGwiLCJ1aWQiOiIxMTA1ODgzNDgxMDExNjU5MTEiLCJhdWQiOiJhZG1pbiIsImlzcyI6ImZlbG9yZC5jbiIsInR5cGUiOiJhY2Nlc3MiLCJleHAiOiIyMDI0LTAxLTI0IDA5OjM5OjExIiwiaWF0IjoiMjAyNC0wMS0yNCAwOTowOToxMSIsImp0aSI6IjI0NWE4ZWFiLWIzNGYtNDE1NS1hZDkzLWE1NDhiNGZjZjgwNyJ9.Gdm2A-J03HHdzVEQBTdA2zwROzhSNZwKmb9lmKXqipwT2yykAjf3LRSWj0k8VBHAwwEqV336qnVgFEBRpwQFhpb6JDLRn84X9xhfuiGUwOZ1PNpNl5gvIqqaNexdtQ__9u5m371DrdE4rg5qwpFHpUm1p0Cr3scAjvjCXhf4HnbT6kFd1jItP__9hao2qpM6McHMZMCBAvMNBsjYQfOb2mPsLzudzu-S-Aow5yFdp2SLRyv9UEe0ITqiYOFlSQkHcE4YMrjYuCK1-OD7YhOdwx6yTclPhrrgLs3tFL7cfhjVoASO1Jfinm4DfcIojp57VGSIUZCtbd0Qqf_fhH3-kw",
    };
  },
  computed: {
    defaultImg() {
      return "this.src=" + require("@/assets/logo.png") + '""';
    },
  },
  mounted() {
    window.layui.use(["table", "form", "jquery","treeSelect"], () => {
      var table = window.layui.table;
      const form = window.layui.form;
      const util = window.layui.util;
      const layer = window.layui.layer;
      const laydate = window.layui.laydate;
      const upload = window.layui.upload;
      const treeSelect = window.layui.treeSelect;
      const $ = window.layui.jquery;
      // 日期初始化
      laydate.render({
        elem: "#date_time",
      });
      laydate.render({
        elem: "#date_time1",
      });
      // 初始化
      uploadFormValue.call(this);
      // 已知数据渲染
      const tableIns = table.render({
        elem: "#ID-table-demo-data",
        url:
          process.env.VUE_APP_BASE_API +
          "/service-eam/gf-vehicle-info/query-paged-list",
        method: "post",
        headers: {
          Authorization:
            "Bearer " +  this.token
        },
        request: {
          //自定义 page  limit
          pageName: "pageIndex",
          limitName: "pageSize",
        },
        cols: [
          [
            //标题栏
            {
              field: "vehiclePhoto",
              title: "照片",
              width: 120,
              templet: (d) => {
                return `
                <div>
                  <img style="width:100px; height:100px;" src="${process.env.VUE_APP_BASE_API + '/service-storage/sys-file/image?id='+ d.vehiclePhoto }"  alt="" />
                </div>
              `;
              },
            },
            { field: "licPlateNum", title: "车牌号码", width: 120 },
            { field: "carBrand", title: "车辆品牌", minWidth: 120 },
            { field: "vehicleType", title: "车辆类型", width: 120 },
            { field: "driver", title: "驾驶员", width: 100 },
            { field: "status", title: "当前状态", width: 120 },
            { field: "registrationDept", title: "所属部门", width: 120 },
            { field: "productionDate", title: "出厂日期", width: 120 },
            { field: "registrant", title: "登记人", width: 120 },
            { field: "registrationDate", title: "登记日期", width: 120 },
            {
              field: "right",
              title: "操作",
              width: 134,
              minWidth: 125,
              fixed: "right",
              toolbar: "#barDemo",
            },
          ],
        ],
        parseData: function (res) {
          return {
            code: res.code, //解析接口状态
            msg: res.message, //解析提示文本
            count: res.data.totalRowCount, //解析数据长度
            data: res.data.list, //解析数据列表
          };
        },
        //skin: 'line', // 表格风格
        //even: true,
        page: true, // 是否显示分页
        limits: [5, 10, 15],
        limit: 5, // 每页默认显示的数量
      });
      util.on("lay-on", {
        openDialog: () => {
          $(".reset_from").click();
          this.addOfEdit = "add";
          form.render();
          this.fileId = "";
          this.departmentId = "";
          // 重置附件
          $(".isShow-style").css("display", "flex");
          $("#ID-upload-demo-preview").addClass("layui-hide");
          this.dialog = layer.open({
            title: "新增车辆",
            type: 1,
            offset: "t",
            anim: 0,
            area: ["800px", "100%"],
            shade: 0.1,
            shadeClose: true,
            id: "ID-demo-layer-direction-t",
            content: $("#add_dialog"),
          });
        },
      });
      // 表单搜索
      form.on("submit(car-search)", async (data) => {
        const field = data.field;
        tableIns.reload({
          url:
            process.env.VUE_APP_BASE_API +
            "/service-eam/gf-vehicle-info/query-paged-list",
          page: {
            pageIndex: 1,
          },
          where: field,
        });
      });
      /** 表单编辑 删除 */
      table.on("tool(ID-table-demo-data)", (obj) => {
        const data = obj.data;
        if (obj.event === "del") {
          const configDialog = layer.confirm(
            "确定删除吗",
            { icon: 3, title: "删除确认" },
            async function () {
              const res = await delVehicleInfo(data.id);
              if (res.code === "00") {
                layer.msg("删除成功", { icon: 1 });
                layer.close(configDialog);
                tableIns.reload();
              } else {
                layer.msg("删除失败", { icon: 2 });
              }
            }
          );
        }
        if (obj.event === "edit") {
          this.addOfEdit = "edit";
          this.departmentId = "";
          this.fileId = "";
          this.dialog = layer.open({
            title: "编辑车辆",
            type: 1,
            offset: "t",
            anim: 0,
            area: ["800px", "100%"],
            shade: 0.1,
            shadeClose: true,
            id: "ID-demo-layer-direction-t",
            content: $("#add_dialog"),
          });
          uploadFormValue.call(this, obj, data,true);
        }
      });
      /** 表单修改 新增 */
      function uploadFormValue(obj, data,isEdit = false) {
        // 回显
        form.val("formTeacherFilter", data);
        // if(this.addOfEdit === 'edit' && data.deptId) {
        //   this.$refs.addDialog.echoData(data?.deptId)
        // }
        if (this.addOfEdit === "edit") {
          this.$refs.addDialog.echoData(data.deptId);
        }
        // 照片回显
        if(isEdit) {
          if(!data.vehiclePhoto) {
            $(".isShow-style").css("display", "flex");
            $("#ID-upload-demo-preview").addClass("layui-hide");
          }else {
            const imageUrl = process.env.VUE_APP_BASE_API + '/service-storage/sys-file/image?id='+ data.vehiclePhoto
          $(".isShow-style").css("display", "none");
            $("#ID-upload-demo-preview")
              .removeClass("layui-hide")
              .find("img")
              .attr("src", imageUrl);
          }
         
        }
        form.on("submit(submit_table)", async (res) => {
          let field = res.field;
          const newArr = {};
          for (let key in field) {
            if (field[key]) {
              newArr[key] = field[key];
            }
          }
          if (this.addOfEdit !== "edit") {
            newArr.vehiclePhoto = this.fileId;
            newArr.deptId = this.departmentId;
            newArr.registrationDept = this.selectName
            const result = await addVehicleInfo(newArr);
            if (result.code === "00") {
              layer.msg("新增成功", { icon: 1 });
              layer.close(this.dialog);
              tableIns.reload();
            } else {
              layer.msg("新增失败", { icon: 2 });
            }
            return;
          }
          newArr.id = data.id;
          newArr.vehiclePhoto = this.fileId || newArr.vehiclePhoto
          newArr.deptId = this.departmentId || newArr.deptId;
          newArr.registrationDept = this.selectName || newArr.registrationDept
          const result = await editVehicleInfo(newArr);
          if (result.code === "00") {
            layer.msg("修改成功", { icon: 1 });
            layer.close(this.dialog);
            tableIns.reload();
          } else {
            layer.msg("修改失败", { icon: 2 });
          }
        });
      }
      // 树形下拉组件
    treeSelect.render({
      // 选择器
      elem: "#tree3",
      // 数据
      data:
        process.env.VUE_APP_BASE_API +
        '/service-hrm/hrm-organization/query-nodes?isLoadAllDescendants=1&targetType="com"',
      // 异步加载方式：get/post，默认get
      type: "post",
      headers: {
        Authorization: "Bearer " + this.token,
      },
      style: {
        folder: {
          // 父节点图标
          enable: true, // 是否开启：true/false
        },
        line: {
          // 连接线
          enable: true, // 是否开启：true/false
        },
      },
      // 占位符
      placeholder: "请选择",
      // 是否开启搜索功能：true/false，默认false
      search: true,
      // 点击回调
      click: (d) => {
        this.departmentId = d.current.id;
        this.selectName = d.current.name
      },
      // 加载完成后的回调函数
      success: (d) => {
        //             // 选中节点，根据id筛选
        // if (this.addOfEdit === "edit") {
        //   treeSelect.checkNode("tree1", this.departmentId);
        // }
      },
    });
      /**  上传图片 */
      upload.render({
        elem: "#ID-upload-demo-drag",
        accept: "file",
        url: process.env.VUE_APP_BASE_API + "/service-storage/sys-file/upload",
        headers: {
          Authorization:
            "Bearer " +
            this.token
        },
        before: (obj) => {
          obj.preview((index, file, result) => {
            this.fileImage = result;
          });
        },
        done: (res) => {
          if (res.code === "00") {
            layer.msg("上传成功");
            $(".isShow-style").css("display", "none");
            $("#ID-upload-demo-preview")
              .removeClass("layui-hide")
              .find("img")
              .attr("src", this.fileImage);
            // 保存文件id
            this.fileId = res.data[0].fileId;
          }
        },
      });
      /** 弹框取消按钮监听 */
      $(".cancel").on("click", () => {
        layer.close(this.dialog);
      });
      form.render();
    });
  },
};
</script>
<style scoped lang="scss">
.realEstate {
  .layui-input-inline {
    width: 150px;
  }
  ::v-deep .layui-table-cell {
    height: auto;
  }
}
.title {
  font-size: 16px;
  color: #000000;
}

.label-width {
  width: 100px;
}

.p-12 {
  padding: 12px;
}

.pt-6 {
  padding-top: 6px;
}

.mt-20 {
  margin-top: 20px;
}

.image {
  width: 50px;
  height: 50px;
}

.operates {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100px;
}
</style>
